package com.mateng.treasurechest.view.recipe.adapter

import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import com.mateng.treasurechest.R
import com.mateng.treasurechest.model.recipe.bean.CategoryBean

/**
 * Created by mateng on 2018/1/25.
 */
class RecipeBigCategoryAdapter(private var childBeans: List<CategoryBean.ResultBean.ChildsBeanX.ChildsBean>?) : RecyclerView.Adapter<RecipeBigCategoryAdapter.ViewHolder>() {

    var onItemClickListener: OnItemClickListener? = null

    var afterClientPosition: Int = 0

    override fun onBindViewHolder(holder: ViewHolder?, position: Int) {
        childBeans?.get(position)?.categoryInfo?.isChecked?.let {
            holder?.itemView?.isSelected = it
        }
        holder?.tvCategoryName?.text = childBeans?.get(position)?.categoryInfo?.name
        holder?.itemView?.setOnClickListener({
            if (afterClientPosition == position)
                return@setOnClickListener

            childBeans?.get(afterClientPosition)?.categoryInfo?.isChecked = false
            afterClientPosition = position
            childBeans?.get(position)?.categoryInfo?.isChecked = true
            notifyDataSetChanged()
            childBeans?.get(position)?.categoryInfo?.ctgId?.let {
                onItemClickListener?.onItemClick(it, position)
            }
        })
    }

    override fun getItemCount(): Int {
        return childBeans?.size ?: 0
    }

    override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): ViewHolder {
        return ViewHolder(LayoutInflater.from(parent?.context).inflate(R.layout.item_recipe_big_category, parent, false))
    }

    inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        val tvCategoryName: TextView = itemView.findViewById(R.id.tv_category_name)
    }

    fun setNewData(childBeans: List<CategoryBean.ResultBean.ChildsBeanX.ChildsBean>) {
        if (childBeans.isNotEmpty()) {
            this.childBeans?.get(afterClientPosition)?.categoryInfo?.isChecked = false
            this.childBeans = childBeans
            afterClientPosition = 0
            childBeans[0].categoryInfo?.isChecked = true
            childBeans[0].categoryInfo?.ctgId?.let { onItemClickListener?.onItemClick(it, 0) }
        }

        notifyDataSetChanged()
    }

    fun getData(): List<CategoryBean.ResultBean.ChildsBeanX.ChildsBean>? = childBeans

    interface OnItemClickListener {
        fun onItemClick(cid: String, position: Int)
    }

}